#include "defined-system-function.h"
#include "game.h"
#include <stdio.h>

#define TOPSCORE_LENGTH 3

HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);

// 二维数组中的坐标和数学中的坐标的x,y是反过来的
void gotoxy(int x, int y)
{
	COORD c;
	c.X = y;
	c.Y = x;
	SetConsoleCursorPosition(handle, c);
}

// 隐藏光标
void hid_cursor()
{
	CONSOLE_CURSOR_INFO info;
	info.bVisible = FALSE;
	info.dwSize = 1;
	SetConsoleCursorInfo(handle, &info);
}

// 设置颜色
void setColor(int color)
{
	if (!color)
	{
		color = 15;
	}
	SetConsoleTextAttribute(handle,color);
}

//0 = 黑色 (Black)
//1 = 蓝色 (Blue)
//2 = 绿色 (Green)
//3 = 青色 (Cyan)
//4 = 红色 (Red)
//5 = 紫色 (Magenta)
//6 = 黄色 (Yellow)
//7 = 白色 (White) 或灰色 (Gray) （取决于是否设置了亮度）
//8 = 深灰色 (Dark Gray) 或亮黑色 (Bright Black) （取决于是否设置了亮度）
//9 = 亮蓝色 (Bright Blue)
//10 = 亮绿色 (Bright Green)
//11 = 亮青色 (Bright Cyan)
//12 = 亮红色 (Bright Red)
//13 = 亮紫色 (Bright Magenta)
//14 = 亮黄色 (Bright Yellow)
//15 = 亮白色 (Bright White)


// 保存分数
void saveGrade(int grade)
{

    FILE* file = fopen("score.txt", "a");
    if (file == NULL)
    {
        return;
    }
    else
    {
        fprintf(file ,"%d\n",grade);
        if (fclose(file) != 0)
        {
            perror("关闭文件时出错");
            return;
        }
        return;
    }
}


// 打印历史最高分
void printTopScore(int grade)
{
	setColor(15);
	int * temp = saveTopGrade(grade);
	for (int i = 0; i < TOPSCORE_LENGTH; i++)
	{
		gotoxy(FACE_Y - 6 + i , 2 * FACE_X + 1);
		printf("历史上最高分：%d",temp[i]);
	}
	free(temp);
}


// 更新历史最高分
int * saveTopGrade(int grade)
{
	FILE * file = fopen("top_score.txt","r+");
	if (file == NULL)
	{
		file = fopen("top_score.txt","w");
	}
	int * temp = (int *)calloc(TOPSCORE_LENGTH + 1,sizeof(int));
	int count = 0;
	while (fscanf(file,"%d",&temp[count++]) != EOF && count < TOPSCORE_LENGTH);
	temp[TOPSCORE_LENGTH] = grade;
	qsort(temp,TOPSCORE_LENGTH + 1,sizeof(int),compare);

	if (temp[TOPSCORE_LENGTH] != grade)
	{
		rewind(file);
		for (int i = 0; i < TOPSCORE_LENGTH; i++)
		{
			fprintf(file,"%d\n",temp[i]);
		}
	}
	fclose(file);
	return temp;
}

// qsort中用到的compare函数
int compare(const void * a,const void * b)
{
	int * x = (int *)a;
	int * y = (int *)b;
	return *y - *x;
}